package logic

import (
	"api/internal/svc"
	"api/internal/types"
	"api/pkg"
	"context"
	"strconv"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type MobileLogLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMobileLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MobileLogLogic {
	return &MobileLogLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MobileLogLogic) MobileLog(req *types.MobileloginRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 手机号登录
	//手机号格式验证
	if !pkg.MobileType(req.Mobile) {
		return &types.RegMsgResponse{
			Code: -2,
			Msg:  "手机号格式错误",
			Data: nil,
		}, err
	}

	//验证码效验
	code, err := l.svcCtx.UserSrv.GetSmsCode(l.ctx, &user.GetSmsCodeRequest{
		Mobile: req.Mobile,
		Sale:   "login",
	})
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	if code.Code != req.Code {
		return &types.RegMsgResponse{
			Code: -2,
			Msg:  "验证码不匹配",
			Data: nil,
		}, err
	}

	//手机号查询是否存在 不存在登录失败
	mobile, err := l.svcCtx.UserSrv.LoginByMobile(l.ctx, &user.LoginByMobileRequest{
		Mobile: req.Mobile,
		Code:   req.Code,
		Sale:   "login",
	})
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "登录失败",
			Data: nil,
		}, err
	}

	//登录成功生成token
	token, err := pkg.GetJwtToken(strconv.FormatInt(mobile.UserId, 10))
	if err != nil {
		return &types.RegMsgResponse{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Code: 0,
		Msg:  "登录成功",
		Data: map[string]interface{}{
			"token": token,
		},
	}, err
}
